const { commentTable, articleTable } = require('../../schemas/index');

const { getResJson, formatTime } = require('../../assets/util');

/**
 * 通过时间范围去查询评论
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 */
exports.searchComment = (params, callback) => {
    let searchJson = {
        commentTime: {
            $gte: params.startTime,
            $lte: params.endTime
        }
    }    
    let count = commentTable.count(searchJson);
    count.exec((err, rs) => {
        commentTable.find(searchJson, (err, data) => {
            let resJson = {};
            if (err) {
                resJson = getResJson(data, '查询失败', false);
            } else {
                let paramsJson = {
                    list: data,
                    total: rs
                }
                resJson = getResJson(paramsJson, '查询成功');
            }
            callback(resJson);
        }).limit(params.pageSize).skip((params.pageNum - 1) * params.pageSize).sort({
            'commentTime': -1
        })
    })
}

/**
 * 删除评论
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 */
exports.deleteComment = (params, callback) => {
    commentTable.findOne({ _id: params._id }, (err, commentInfo) => {
        commentTable.deleteOne({ _id: params._id }, (err, data) => {
            let resJson = {};
            if (err) {
                resJson = getResJson(data, '删除失败', false);
            } else {
                articleTable.updateOne({ _id: commentInfo.articleId }, { $inc: { commentTotal: -1 } },err => {
                    if(err){
                        console.log('---------');
                        console.log(err);
                        console.log(`${params.articleTitle} - 评论总数自增失败`);
                        
                    }
                })
                resJson = getResJson(data, '删除成功');
            }
            callback(resJson);
        })
    })
}